// use std::env;
// use std::sync::OnceLock;
// use diesel::prelude::*;
// use diesel::r2d2::{ConnectionManager, PooledConnection};

// #[derive(diesel::MultiConnection)]
// pub enum AnyConnection {
//   Sqlite(diesel::SqliteConnection)
// }


// pub type Pool = diesel::r2d2::Pool<ConnectionManager<SqliteConnection>>;

// pub struct DataSourcePool;

// static DATASOURCE_POOL: OnceLock<Pool> = OnceLock::new();


// impl DataSourcePool {
//     pub fn setup() -> &'static Pool {
//         DATASOURCE_POOL.get_or_init(|| {
//             // 从环境变量读取数据库 URL
//             let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| {
//                 eprintln!("DATABASE_URL not found");
//                 std::process::exit(1);
//             });
//             // 创建数据库连接池
//             Pool::builder()
//                 .build(ConnectionManager::new(database_url))
//                 .expect("Failed to create pool.")
//         })
//     }

//     pub fn get_connection() -> PooledConnection<ConnectionManager<SqliteConnection>> {
//         DATASOURCE_POOL.get()
//             .expect("Failed to get a connection from the pool.")
//             .get().expect("Failed to get a connection from the pool.")
//     }
// }
use async_once::AsyncOnce;
use lazy_static::lazy_static;

use std::env;

use dotenvy::dotenv;
use diesel::prelude::*;
use diesel::r2d2::ConnectionManager;
use diesel::r2d2::Pool;

#[derive(diesel::MultiConnection)]
pub enum AnyConnection {
    // Postgresql(diesel::PgConnection),
    // Mysql(diesel::MysqlConnection),
    Sqlite(diesel::SqliteConnection),
}

pub type DbPool = Pool<ConnectionManager<diesel::SqliteConnection>>;

/**
 * 获取连接池
 */
fn get_connection_pool() -> DbPool {
  dotenv().ok();
  let url = env::var("DATABASE_URL").unwrap_or_else(|_| {
                    eprintln!("DATABASE_URL not found");
                    std::process::exit(1);
                });
  // Refer to the `r2d2` documentation for more methods to use
  // when building a connection pool
  Pool::builder()
      .test_on_check_out(true)
      .build(ConnectionManager::new(url))
      .expect("Could not build connection pool")
}

lazy_static! {
  pub static ref DB_POOL: AsyncOnce<DbPool> = AsyncOnce::new( async {
    get_connection_pool()
  });
}
